<template>
  <div class="search-result-page">


    <!-- 浮窗 -->
    <div
      class="filter-fab"
      @mouseenter="hovered = true"
      @mouseleave="hovered = false"
      @click="filterVisible = true"
    >
      <el-icon><Filter /></el-icon>
      <span class="label" v-show="hovered">筛选</span>
    </div>

    <!-- 抽屉 -->
    <el-drawer
    v-model="filterVisible"
    title="筛选商品"
    direction="rtl"
    size="260px"
    >

    <h4 style="margin-top: 20px;">排序：</h4>

    <el-radio-group v-model="sortBy" class="compact-radios">
      <el-radio label="time">最新上架</el-radio>
      <el-radio label="price">价格</el-radio>
      <el-radio label="sales">销量</el-radio>
    </el-radio-group>
    <el-radio-group v-model="sortOrder" style="display: block;">
    <el-radio-button label="asc">升序</el-radio-button>
    <el-radio-button label="desc">降序</el-radio-button>
    </el-radio-group>

    <h4>按类目：</h4>
    <el-radio-group v-model="selectedCatId">
        <el-radio
        v-for="c in categories"
        :key="c.id"
        :label="c.id"
        >
        {{ c.name }}
        </el-radio>
    </el-radio-group>

    <h4 style="margin-top: 20px;">按价格区间：</h4>
    <el-input-number
    v-model="minPrice"
    :min="0"
    :step="1"
    :precision="0"
    placeholder="最低价"
    style="width: 100%; margin-bottom: 12px;"
    />

    <el-input-number
    v-model="maxPrice"
    :min="0"
    :step="1"
    :precision="0"
    placeholder="最高价"
    style="width: 100%;"
    />

    <h4 style="margin-top: 20px;">按库存量：</h4>
    <el-input-number
    v-model="minStock"
    :min="0"
    :step="1"
    :precision="0"
    placeholder="最小库存"
    style="width: 100%;"
    />

    <div class="drawer-footer">
        <el-button @click="resetFilter">清空</el-button>
        <el-button type="primary" @click="applyFilter">确定</el-button>
    </div>
    </el-drawer>

    <!-- 商品列表 -->
    <el-row :gutter="20" class="product-grid" v-loading="loading">
    <el-col
        v-for="item in result"
        :key="item.id"
        :span="6"
        class="product-card"
    >
        <el-card :body-style="{ padding: '0px' }">
        <img :src="item.mainImage" class="product-image" />
        <div class="product-info">
            <h3>{{ item.title }}</h3>
            <p class="price">￥{{ item.price }}</p>
            <el-button
            type="primary"
            size="small"
            @click="viewProduct(item.id)"
            >
            查看详情
            </el-button>
        </div>
        </el-card>
    </el-col>
    </el-row>

    <!-- 空状态 -->
    <el-empty
    v-if="!loading && result.length === 0"
    description="暂无相关商品"
    />

    <!-- 分页 -->
    <el-pagination
    v-if="total"
    class="pagination-container"
    background
    layout="total, prev, pager, next"
    :total="total"
    :page-size="pageSize"
    :current-page="currentPage"
    @current-change="handlePageChange"
    />
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRoute ,useRouter} from 'vue-router'
import { ElMessage } from 'element-plus'
import { Filter } from '@element-plus/icons-vue'
import { searchProducts,getProductWithSku } from '@/api/product'

/* 路由 */
const route   = useRoute()
const router = useRouter();
const keyword = ref(route.query.q || '')

/* 列表 分页 */
const result      = ref([])
const loading     = ref(false)
const currentPage = ref(1)
const pageSize    = ref(8)
const total       = ref(0)

/* 分类筛选相关 */
const categories     = ref([])
const selectedCatId = ref(null)
const filterVisible  = ref(false)
const hovered        = ref(false)
const minPrice = ref(null)
const maxPrice = ref(null)
const minStock = ref(null)
const sortBy    = ref('time')
const sortOrder = ref('desc')


/* 搜索 */
const fetchSearch = async () => {
  if (!keyword.value.trim()) return
  loading.value = true
  try {
    const dto = {
    keyword   : keyword.value.trim(),
    categoryId: selectedCatId.value || null,
    minPrice  : minPrice.value,
    maxPrice  : maxPrice.value,
    minStock  : minStock.value,
    sortBy    : sortBy.value,
    sortOrder : sortOrder.value,
    pageNum   : currentPage.value,
    pageSize  : pageSize.value
    }
    const res = await searchProducts(dto)
    console.log('搜索的数据结构：', res)
    if (res.data.code !== '200') throw new Error(res.message || '搜索失败')
   const { page, categoryList } = res.data.data
   result.value   = page.list
   total.value    = page.total
   pageSize.value = page.pageSize
   categories.value = categoryList           // ← 把类目塞进抽屉
  } catch (e) {
    ElMessage.error(e.message || '搜索失败')
    result.value = []
  } finally {
    loading.value   = false
  }
}

/* 抽屉按钮 */
const applyFilter = () => {
  if (minStock.value != null && minStock.value < 0) {
    ElMessage.warning("最小库存不能为负数")
    return
  }
  if (
    minPrice.value != null &&
    maxPrice.value != null &&
    minPrice.value > maxPrice.value
  ) {
    ElMessage.warning("最小价格不能大于最大价格")
    return
  }

  filterVisible.value = false
  fetchSearch()
}

const resetFilter = () => {
  selectedCatId.value = null
  minPrice.value = null
  maxPrice.value = null
  minStock.value = null
  sortBy.value    = 'time'
  sortOrder.value = 'desc'
  fetchSearch()
}

const viewProduct = async (productId) => {
  if (!productId) {
    ElMessage.error('商品 ID 缺失');
    return;
  }
  try {
    const res = await getProductWithSku(productId);
    if (res.data.code == 200 || res.data.code == '200') {
      router.push({ name: 'ProductDetail', params: { id: productId } });
    } else {
      ElMessage.error(res.data.message || '商品不存在');
    }
  } catch (error) {
    console.error('获取商品详情失败:', error); // 打印详细错误
    ElMessage.error('获取商品详情失败');
  }
};

const handlePageChange = (p) => {
  currentPage.value = p
  fetchSearch()
}

/* 监听关键词变动 */
watch(
  () => route.query.q,
  (q) => {
    // 没有关键词就别请求
    if (!q || !q.trim()) return
    keyword.value = q.trim()
    fetchSearch()
  },
  { immediate: true }
)

</script>

<style scoped>
.product-grid {
  margin-top: 20px;
}

.product-card {
  margin-bottom: 20px;
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 12px 12px 0 0;
}

.product-info {
  padding: 14px 10px 10px;
  text-align: center;
  background: #fafbfc;
  border-radius: 0 0 12px 12px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
  margin: 8px 0;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}


/* 浮窗按钮 */
.filter-fab{
  position:fixed; top:120px; right:-28px;
  width:70px;height:70px;border-radius:50%;opacity: 0.85;
  background:#409eff;color:#fff;cursor:pointer;
  display:flex;align-items:center;justify-content:center;
  box-shadow:0 2px 8px rgba(0,0,0,.2);transition:right .2s;
}
.filter-fab {
  top: 140px;
}
.filter-fab:hover{ right:16px }
.filter-fab .label{ margin-left:6px;font-size:16px }

/* 抽屉底部 */
.drawer-footer{
  position:absolute;bottom:16px;left:0;width:100%;text-align:center;
}

.compact-radios .el-radio {
  margin-right: 10px; 
}
.compact-radios .el-radio:last-child {
  margin-right: 0;  
}
</style>
